package io.afu.baseframework.controller;

import io.afu.baseframework.annotations.BSLog;
import io.afu.baseframework.dto.resp.BaseResp;
import io.afu.baseframework.enums.ConstantEnum;
import io.afu.baseframework.exceptions.BaseException;
import io.afu.baseframework.exceptions.NorightException;
import io.afu.baseframework.exceptions.SessionExpException;
import io.afu.baseframework.utils.WebHttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletResponse;

/**
 * @author RffanLAB.方露宇
 * @version 0.1
 */
@RestControllerAdvice
public class ExceptionController {


    private Logger logger = LoggerFactory.getLogger(getClass());


    private void logErrRequestBody() {
        HttpServletRequest request = WebHttpUtil.getRequest();
        if (request != null) {
            String header = WebHttpUtil.parseRequestHeaders(request);
            String param = WebHttpUtil.parseParams(request);
            String body = WebHttpUtil.parseBodyParams(request);
            String ip = WebHttpUtil.getIP(request);
            logger.error("报错接口请求信息: \n" +
                    "请求ip：[" + ip + "]\n" +
                    "请求头：[" + header + "]\n" +
                    "请求头参数：[" + param + "]\n" +
                    "请求体参数：[" + body + "]\n");
        }

    }

    @ExceptionHandler({BaseException.class})
    @BSLog
    public BaseResp handlerException(BaseException e, HttpServletResponse response){
        logger.info("[接口访问出错]",e);
        logErrRequestBody();
        if (ConstantEnum.USER_SESSION_EXPIRED.getCode().equals(e.getCode())){
            response.setStatus(401);
        }
        if ("403".equals(e.getCode())){
            response.setStatus(403);
        }
        return BaseResp.fail(e);
    }

    @ExceptionHandler({SessionExpException.class})
    @BSLog
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public BaseResp handlerException(SessionExpException e) {
        logErrRequestBody();
        return BaseResp.fail(e);
    }


    @ExceptionHandler({NorightException.class})
    @BSLog
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public BaseResp handlerException(NorightException e) {
        logErrRequestBody();
        return BaseResp.fail(e);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @BSLog
    public BaseResp handlerException(MethodArgumentNotValidException e){
        logErrRequestBody();
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach( err -> stringBuilder.append("参数：").append(err.getField()).append(":").append(err.getDefaultMessage()).append(";"));
        return BaseResp.fail(stringBuilder.toString(),ConstantEnum.PARAM_ERROR.getCode());
    }

    @ExceptionHandler({ Exception.class })
    @BSLog
    public BaseResp exception(Exception e) {
        logger.error(e.getMessage(),e);
        logErrRequestBody();
        return BaseResp.fail(e);
    }








}
